#include "Common.fxh"

cbuffer cbLight
{
	float3 Direction;
	float3 Color;
	float Intensity;
};

struct VS_INPUT
{
    float2 Pos : Position;
    float2 Tex : TexCoord;
};

struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : Tex;
	float2 ScreenPosition : TexCoord1;
};

struct PS_OUTPUT
{
	float4 DiffuseColor : SV_TARGET0;
	float4 SpecularColor : SV_TARGET1;
};

PS_INPUT VS(VS_INPUT input)
{
    PS_INPUT output;

    output.Pos = float4(input.Pos, 0, 1);
    output.Tex = input.Tex;
    output.ScreenPosition = input.Tex * 2.0;
    output.ScreenPosition.x = output.ScreenPosition.x - 1.0;
    output.ScreenPosition.y = 1.0 - output.ScreenPosition.y;

    return output;
}

PS_OUTPUT PS(PS_INPUT input)
{
	PS_OUTPUT output = (PS_OUTPUT)0;

	float4 normalData = Normal.Sample(samLinear, input.Tex);
	float3 normal = (2.0 * normalData.xyz) - 1.0;
	float specularPower = normalData.a * 255;
	float specularIntensity = Diffuse.Sample(samLinear, input.Tex).a;
	float depthVal = Depth.Sample(samLinear, input.Tex).r;
	
	float4 position = float4(input.ScreenPosition, depthVal, 1.0f);
	
	position = mul(position, InverseViewProj);
	position /= position.w;
	
	float3 lightVector = normalize(-Direction);
	
	float NdL = max(0, dot(normal, lightVector));
	float3 diffuseLight = NdL * Color;
	
	float3 reflectionVector = normalize(reflect(-lightVector, normal));
	float3 surfaceToCamera = normalize(CameraPosition - position.xyz);
	float specularLight = specularIntensity * pow(saturate(dot(reflectionVector, surfaceToCamera)), specularPower);
	
	output.DiffuseColor.rgb = Intensity * diffuseLight;
	output.SpecularColor = Intensity * specularLight;
	
	return output;
}

technique10 Render
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PS() ) );
    }
}